package com.atkxp.service.impl;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.atkxp.dao.OrderDao;
import com.atkxp.dao.OrderItemDao;
import com.atkxp.dao.impl.OrderDaoImpl;
import com.atkxp.dao.impl.OrderItemDaoImpl;
import com.atkxp.domain.*;
import com.atkxp.service.BookService;
import com.atkxp.service.OrderService;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.Map;
import java.util.*;

/**
 * @author user
 * @declaration
 * @create 2022/10/5-10:25
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();

    private BookService bookService = new BookServiceImpl();
    @Override
    public String createOrder(Cart cart, int user_id) {
        String orderId = System.currentTimeMillis() + "" + user_id;
        Order order = new Order(orderId, new Date(new java.util.Date().getTime()), cart.getTotalPrice(), 0, user_id);
        orderDao.saveOrder(order);
        for(Map.Entry<Integer, CartItem> map : cart.getItems().entrySet()){
            CartItem cartItem = map.getValue();
            OrderItem orderItem = new OrderItem(0, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            orderItemDao.saveOrderItem(orderItem);
            Book book = bookService.queryBookById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookService.updateBook(book);
        }
        cart.clear();
        return orderId;
    }

    @Override
    public List<Order> showAllOrders() {
        return orderDao.queryOrders();
    }

    @Override
    public int sendOrder(String orderId) {
        return orderDao.changeOrderStatus(orderId, 1);
    }

    @Override
    public List<OrderItem> showOrderDetails(String orderId) {
        return orderItemDao.queryOrderItemsByOrderId(orderId);
    }

    @Override
    public List<Order> showMyOrders(int userId) {
        return orderDao.queryOrderByUserId(userId);
    }

    @Override
    public int receiveOrder(String orderId) {
        return orderDao.changeOrderStatus(orderId, 2);
    }
}
